﻿/*
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Text;
namespace Scaffold.Views
{
    /* REVIEW: 
     * aspnet_compiler.exe seems to generate this page a couple of different ways
     * in some cases it adds a literal control in BuildControlContent, in others 
     * it does something like ctrl.SetRenderMethodDelegate(new RenderMethod(this.__RenderContent1));
     * I do not understand what the difference between these code paths is.
     */


    public abstract class ScaffoldViewPage<TItem> :  ViewPage<TItem>, IHttpHandler
    {

        protected ViewPageInfo ViewInfo { get; set; }
        private static object _fileDependencies;
        private static bool _initialized;


        public ScaffoldViewPage(ViewPageInfo viewInfo)
        {
            ViewInfo = viewInfo;
            string[] virtualFileDependencies = new string[] { ViewInfo.MasterPage };
            _fileDependencies = base.GetWrappedFileDependencies(virtualFileDependencies);
            base.AppRelativeVirtualPath = ViewInfo.RelativeVirtualPath;
        }


        protected abstract void BuildContent(StringBuilder builder);
        protected void BuildControlContent(Control ctrl)
        {

            IParserAccessor accessor = ctrl;
            StringBuilder sb = new StringBuilder();
            BuildContent(sb);
            accessor.AddParsedSubObject(new LiteralControl(sb.ToString()));
        }
        
        
        protected void BuildControlTree(ScaffoldViewPage<TItem> ctrl)
        {
            ctrl.MasterPageFile = ViewInfo.MasterPage;
            ctrl.Title = ViewInfo.Title;
            this.InitializeCulture();
            base.AddContentTemplate(ViewInfo.ContentPlaceHolderID, new CompiledTemplateBuilder(new BuildTemplateMethod(this.BuildControlContent)));

        }


        protected override void FrameworkInitialize()
        {
            base.FrameworkInitialize();
            this.BuildControlTree(this);
            base.AddWrappedFileDependencies(_fileDependencies);
            base.Request.ValidateInput();
        }

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
        }
    }
}
